package ochart.utils
{
	import ochart.core.Color;

	public class ColorUtil
	{
		public static function getColor(name:String):uint
		{
			name = name.toUpperCase();
			return (Color.color[name] === undefined) ? 0 : Color.color[name];
		}
		
		public static function getName(color:uint):String
		{
			for(var name:String in Color.color)
			{
				if(Color.color[name] == color)
				{
					return name;
				}
			}
			return null;
		}
		
		public static function fixColor(value:*):uint
		{
			var color:uint = 0xff0000
			if(value == null || value === undefined)
			{
				return color;
			}
			if(value is String)
			{
				color = convertStringHexColorToUint(String(value));
			}
			return color;
		}
		
		public static function convertStringHexColorToUint(value:String):uint
		{
			if(value.length == 8 && StringUtil.beginsWith(value, "0x"))
			{
				return uint(value);
			}
			
			if(isStringHexColor(value) == false)
			{
				return 0xff0000;
			}
			
			if(value.indexOf("#") == 0)
			{
				value = value.substring(1);
			}
			
			if(value.length == 3)
			{
				var newValue:String = "";
				for(var index:int = 0; index < value.length; index++)
				{
					newValue += value.charAt(index) + value.charAt(index);
				}
				value = newValue;
			}
			
			value = StringUtil.addZero(value, 6);
			
			return uint("0x" + value);
		}
		
		/**
		*  验证字符串是否为颜色值
		* 
		*  @param 待验证的字符串
		* 
		*  @return 返回是否通过验证的布尔值
		*/
		public static function isStringHexColor(v:String, strict:Boolean = false):Boolean
		{
			var regExpStr:String = "[#]?[0-9a-fA-F]{1,6}";
			if(strict == true)
			{
				regExpStr = "^#[0-9a-fA-F]{1,6}$";
			}
			var regExp:RegExp = new RegExp(regExpStr);
			return regExp.test(v);
		}
	}
}